<template>
  <!-- 轮播图 -->
  <el-carousel class="light" indicator-position="outside">
    <el-carousel-item v-for="(item, index) in carouselItems" :key="index" style="height: 400px">
      <img :src="item.src" style="height: 400px;width:1250px; object-fit: cover;">
      <h3 text="2xl" justify="center">{{ item.text }}</h3>
    </el-carousel-item>
  </el-carousel>
  <div class="container">

    <!-- 折线图和公告栏容器 -->
    <el-row class="content-row" :gutter="20" style="margin-top: 20px; margin-left: 50px;">
      <!-- 折线图模块 -->
      <el-col :span="14">
        <div class="module chart-module">
          <el-card class="module-card">
            <div class="module-title">每月用电和用水统计</div>
            <div ref="lineChart" class="chart"></div>
            <div ref="pieChart" class="chart" style="margin-top: 20px;"></div>
          </el-card>
        </div>
      </el-col>

      <!-- 公告栏模块 -->
      <el-col :span="10">
        <div class="module announcement-module">
          <el-card class="module-card">
            <div class="module-title">公告栏</div>
            <el-timeline>
              <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :timestamp="activity.time"
              >
                {{ activity.content }}
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.container{
  margin-top: 500px;
}
.light{
  position: absolute;
  margin-top: 50px;
  margin-left: 250px;
  width:1250px;
  height:400px;
}

.el-carousel__item h3 {
  color: #c45656;
  opacity: 0.75;
  display: flex;
  align-items: center;
  margin: 0;
  text-align: center;
  height: 100%;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.content-row {
  margin-top: 500px;
}

.module {
  border: 1px solid #fff; /* 模块边框 */
  padding: 10px;
  margin: 0 10px; /* 模块间距 */
}

.module-title {
  text-align: left; /* 模块标题左对齐 */
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.chart {
  width: 100%;
  height: 400px;
}

.el-timeline-item__content {
  text-align: left; /* 公告内容左对齐 */
}
</style>

<script lang="ts">
import { defineComponent, ref, onMounted, reactive } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';

interface User {
  ordId: string;
  userId: string;
  realname: string;
  usedWater: string;
  waSum: string;
  usedElc: string;
  elSum: string;
  sum: string;
  addtime: string;
}

export default defineComponent({
  name: 'LineChart',
  setup() {
    const activities = ref([
      {
        time: '2024-01-01',
        content: '新年快乐！感谢您一直以来的支持。'
      },
      {
        time: '2024-01-15',
        content: '系统维护通知：我们将在1月15日22:00至23:00进行系统维护。'
      },
      {
        time: '2024-02-01',
        content: '春节放假通知：我们的服务将在春节期间暂停，2月1日至2月7日。'
      },
      {
        time: '2024-07-15',
        content: '系统升级通知：我们将于7月20日23:00至次日02:00进行系统升级，届时将暂停服务。'
      },
      {
        time: '2024-09-30',
        content: '节假日服务调整：国庆节期间（10月1日至10月7日）服务时间将做出相应调整。'
      },
      {
        time: '2024-10-01',
        content: '温馨提示：本月账单已生成，请及时支付以避免逾期产生额外费用。点击这里查看账单详情。'
      },
      // 更多公告...
    ]);

    const data = reactive({
      home: {
        ordId: '',
        userId: '',
        realname: '',
        usedWater: '',
        waSum: '',
        usedElc: '',
        elSum: '',
        sum: '',
        addtime: ''
      },
      homes: [] as User[]
    });

    const carouselItems = ref([
      { src: 'C:\\Users\\10616\\Desktop\\xmsx\\frontend\\sbb\\src\\assets\\mt.jpg', text: '轮播图1' },
      { src: 'C:\\Users\\10616\\Desktop\\xmsx\\frontend\\sbb\\src\\assets\\gpt.png', text: '轮播图2' },
      { src: 'C:\\Users\\10616\\Desktop\\xmsx\\frontend\\sbb\\src\\assets\\error.png', text: '轮播图3' },
      { src: 'C:\\Users\\10616\\Desktop\\xmsx\\frontend\\sbb\\src\\assets\\blue.png', text: '轮播图4' }
    ]);

    const lineChart = ref(null);
    const pieChart = ref(null);

    onMounted(() => {
      initChart();
    });

    const initChart = async () => {
      const chart = echarts.init(lineChart.value);
      const pie = echarts.init(pieChart.value);

      // 获取数据
      const response = await axios.get('http://localhost:8080/home', {
        params: {
          userId: JSON.parse(localStorage.getItem('user') || '{}').userId,
        },
      });

      // 假设后端返回的数据结构中包含 homes 数组
      const homes = response.data;

      // 获取当前月份
      const currentMonth = new Date().getMonth() + 1;

      // 处理数据，确保每月1日的 addtime 数据显示的是上一个月的用电量和用水量数据
      const lineChartData = homes
          .filter((home: User) => {
            const month = parseInt(home.addtime.substring(5, 7));
            return month < currentMonth; // 只显示当前月份之前的完整月份的数据
          })
          .map((home: User) => ({
            month: home.addtime.substring(5, 7) + '月',
            usedElc: home.usedElc,
            usedWater: home.usedWater
          }));

      // 按月份排序
      lineChartData.sort((a, b) => parseInt(a.month) - parseInt(b.month));

      // 提取数据
      const months = lineChartData.map(data => data.month);
      const usedElcData = lineChartData.map(data => data.usedElc);
      const usedWaterData = lineChartData.map(data => data.usedWater);

      const option = {
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['用电量', '用水量']
        },
        xAxis: {
          type: 'category',
          data: months // 显示月份数据
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '用电量',
            type: 'line',
            data: usedElcData, // 使用从API获取的数据
            itemStyle: {
              color: '#5470C6' // 用电量线的颜色
            }
          },
          {
            name: '用水量',
            type: 'line',
            data: usedWaterData, // 使用从API获取的数据
            itemStyle: {
              color: '#91CC75' // 用水量线的颜色
            }
          }
        ]
      };

      chart.setOption(option);

      // 饼状图数据
      const totalUsedElc = usedElcData.reduce((sum, value) => sum + parseFloat(value), 0);
      const totalUsedWater = usedWaterData.reduce((sum, value) => sum + parseFloat(value), 0);

      const pieOption = {
        title: {
          text: '用电量和用水量比例',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['用电量', '用水量']
        },
        series: [
          {
            name: '用量',
            type: 'pie',
            radius: '50%',
            data: [
              { value: totalUsedElc, name: '用电量' },
              { value: totalUsedWater, name: '用水量' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      pie.setOption(pieOption);
    };

    return {
      activities,
      data,
      carouselItems,
      lineChart,
      pieChart,
      initChart
    };
  }
});
</script>
